package com.algorithm;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue;

import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 分库策略
 */
@Slf4j
public class DatabaseStrategyAlgorithms implements ComplexKeysShardingAlgorithm {


    @Override
    public Collection<String> doSharding(Collection availableTargetNames, ComplexKeysShardingValue shardingValue) {
        Map<String,Object> columnNameAndShardingValuesMap = shardingValue.getColumnNameAndShardingValuesMap();
        log.info("所有的sharding列的值为:{}", JSON.toJSONString(columnNameAndShardingValuesMap));
        for (Map.Entry<String,Object> entry: columnNameAndShardingValuesMap.entrySet()) {
            String shardColumn = entry.getKey();
            Object shardValue = entry.getValue();
        }
        Set<String> result = new HashSet<>();
        Collection idColl = (Collection)columnNameAndShardingValuesMap.get("id");
        for (Object idObj: idColl) {
            if (idObj instanceof Integer || idObj instanceof Long) {
                long idTemp = Long.parseLong(idObj.toString());
                long target = idTemp % 2;
                for (Object targetNames:availableTargetNames) {
                    if (targetNames.toString().endsWith(target + "")) {
                        result.add(targetNames.toString());
                    }
                }
            }
        }
        log.info("complex算法result:{}", JSON.toJSONString(columnNameAndShardingValuesMap));
        return result;
    }
}
